http = require 'http'
koa = require('koa')
koaBody = require('koa-body')

enableDestroy = require('server-destroy')
Promise = require 'bluebird'

config = require './config'
log = require './log'
errors = require './errors'
mongo = require './mongoStore'

app = koa()
app.keys = [config.cookieKey]
app.proxy = true

require('koa-validate')(app)

app.use(koaBody(multipart: true, formidable: {uploadDir: config.uploadPath, keepExtensions: true}))

app.use(require('./jade').jade.middleware)

UserService = require('./service/UserService')

# 不管是否需要登录,都获取用户信息
app.use (next)->
    userId = this.cookies.get('user_id', {signed: true})
    # userId = userId && mongo.stringToObjectId(userId)
#    userToken = this.cookies.get('user_token', {signed: true})

    if userId
        session = yield from UserService.gAuthenticate(userId)

        if session
            this.state.userId = userId
#            this.state.idName = session.idName
            this.state.username = session.username
#            this.state.userPermissions = session.permissions
        else
            delete this.state.userId
    yield next

router = require('./router').getRouter()
app.use(router.routes()).use(router.allowedMethods())

# ==========

server = http.createServer(app.callback())
exports.server = server

server.on 'error', (err) -> log.system.error 'Error on server!', err

enableDestroy(server)

exports.start = ->
    yield Promise.promisify(server.listen.bind(server))(config.serverPort)
    log.system.info 'Web Server Up!'